<?php

namespace App\Listeners;

use App\Events\ConfigChangeEvent;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Cache;

class ConfigChangeListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  ConfigChangeEvent $event
     * @return void
     */
    public function handle(ConfigChangeEvent $event)
    {
        //生成系统配置文件缓存
        Cache::store('file')->forget('configs');

        $file_path = storage_path('framework/cache') . '/configs.php';
        if (file_exists($file_path)) unlink($file_path);
        $this->configs($file_path);
    }

    public function configs($file_path)
    {
        $str = '<?php';
        $str .= "\r\n\r\nreturn [";
        //首先获取系统所有配置
        $configs = Cache::store("file")->rememberForever("configs", function () {
            return \App\Models\Site::all();
        });
        foreach ($configs as $val) {
            //debug的布尔值不加单引号
            if ($val->var_key == 'debug') {
                $str .= "\r\n'" . $val->var_key . "' => " . $val->var_value . ",";
            } else {
                $str .= "\r\n'" . $val->var_key . "' => " . "'" . $val->var_value . "',";
            }
        }
        $str .= '];';
        return file_put_contents($file_path, $str);
    }
}
